package com.rmb.util;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author wan
 * @Title: Demo01
 * @Package util
 * @Description: wan
 * @date 2021/1/1311:21
 */
public class Demo01 {

    public static void main(String[] args) throws Exception {
        String etl = "ss";
          String code = "public class "+etl+" {\n" +
                  "    \n" +
                  "    public static void main(String[] args) {\n" +
                  "        System.out.println(\"HelloWord\");\n" +
                  "    }\n" +
                  "    \n" +
                  "}";
        File file = new File("F:/ahtml/java/"+etl+".java");
        if(!file.exists()){
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(code.getBytes(),0,code.length());
        outputStream.flush();
        outputStream.close();
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //将Java代码以字符串的形式，先写入文件，然后再通过编译器读取出来，达到动态的效果。
        //InputStream in, OutputStream out, OutputStream err, String... arguments
        int run2 = compiler.run(null, null, null, "F:/ahtml/java/"+etl+".java");
        System.out.println(run2==0?"编译成功":"编译失败");
        //通过Runtime类动态运行编译好的类
        Runtime runtime = Runtime.getRuntime();
        //实际上已经执行了
        Process pro = runtime.exec("java -cp F:/ahtml/java "+etl);
        //输出到控制台
        InputStream in = pro.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String temp = "";
        while((temp = reader.readLine())!=null){
            System.out.println(temp);
        }

        //通过类加载器来动态运行编译好的类
        URL[] urls = {new URL("file:/" + "F:/ahtml/java/")};
        URLClassLoader loader = new URLClassLoader(urls);
        Class<?> c = loader.loadClass(etl);
        //调用加载类的mian方法
        Method main = c.getMethod("main", String[].class);
        main.invoke(c.newInstance(), (Object) new String[]{"aa","bb"});
    }

}
